from django.shortcuts import render
from django.views import View
from elasticsearch import Elasticsearch
from rest_framework.status import HTTP_404_NOT_FOUND

from config.elastic.elasticSearchConfig import HOST, PORT
from config.fastdfs.config import FASTDFS_SERVER_DOMAIN
import logging
logger = logging.getLogger(__name__)

from fdfs_client.client import get_tracker_conf, Fdfs_client
from rest_framework.response import Response
from rest_framework import viewsets, status
# Create your views here.
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet

from shopping.models import GoodsType, Commodity, CommodityImg
from shopping.serializers import GoodsTypeSerializers, ParentSerializers, CommoditySerializer, CommodityImgSerializer
from utils.permission import TeacherPermission, wrap_premission


class GoodsTypeViews(viewsets.ModelViewSet):
    queryset = GoodsType.objects.all()
    serializer_class = GoodsTypeSerializers
    def get_queryset(self):
        if self.action =='list':
            return GoodsType.objects.filter(parent_id=None)
        return self.queryset
    def get_serializer_class(self):
        if self.action == 'list' or self.action == 'retrieve':
            return ParentSerializers
        return GoodsTypeSerializers

    @wrap_premission(TeacherPermission)  # 只有老师才能添加商品类型的数据
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @wrap_premission(TeacherPermission)  # 只有老师才能修改商品类型的数据
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @wrap_premission(TeacherPermission)  # 只有老师才能删除商品类型的数据
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)


tracker_path = get_tracker_conf('utils/fastdfs/client.conf')
client = Fdfs_client(tracker_path)
en = Elasticsearch([{'host':HOST,'port':PORT}])

class CommodityViewSet(viewsets.ModelViewSet):
    queryset = Commodity.objects.filter(is_delete=False)
    serializer_class = CommoditySerializer
    permission_classes = [IsAuthenticated]

    @wrap_premission(TeacherPermission)
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        res_data = serializer.data
        en.index(index='commodity',id=res_data['id'],body=serializer.data)
        return ModelViewSet.create(self, request, *args, **kwargs)

    @wrap_premission(TeacherPermission)
    def update(self, request, *args, **kwargs):
        try:
            commodity = Commodity.objects.get(pk=kwargs['pk'])
        except:
            return Response(status=HTTP_404_NOT_FOUND)
        serializer = self.get_serializer(instance=commodity,data=request.data)
        serializer.is_valid(raise_exception = True)
        serializer.save()
        data = {}
        data['doc'] = serializer.data
        # es的update方法，要把数据包括在doc里面，做成一个键值对的形式然后才可以，不然会报错
        en.update(id=kwargs['pk'],index='commodity',body=data)
        return ModelViewSet.update(self, request, *args, **kwargs)

    @wrap_premission(TeacherPermission)
    def destroy(self, request, *args, **kwargs):
        en.delete(id=str(int(kwargs['pk'])-1),index='commodity')
        return ModelViewSet.destroy(self, request, *args, **kwargs)
    @action(methods=['post'], detail=True)
    def img(self, request, pk):
        try:
            commodity = self.get_queryset().get(id=pk)
        except commodity.DoesNotExist:
            return Response(status.HTTP_404_NOT_FOUND)
            # 上传图片
            # 得到上传的文件数据
        avatar = request.FILES.get('file')
        print(avatar)

        if not avatar or avatar.content_type not in ('image/jpeg', 'image/png', 'image/gif'):
            # 不是，返回客户端传入数据错误
            return Response(status=status.HTTP_400_BAD_REQUEST)

            # 得到文件后缀名，如果没有后缀名则默认为png类型
        try:
            images_ext_name = avatar.name.split('.')[-1]
        except Exception as e:
            logger.info('图片拓展名异常：%s' % e)
            images_ext_name = 'png'

        # 上传图片数据，通过字节流
        try:
            upload_res = client.upload_by_buffer(avatar.read(), file_ext_name=images_ext_name)
        except Exception as e:
            logger.error('图片上传出现异常：%s' % e)
            return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if upload_res.get('Status') != 'Upload successed.':
                logger.warning('图片上传失败')
                return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            # 得到返回的file_id
            image_name = upload_res.get('Remote file_id').decode()
            image_url = FASTDFS_SERVER_DOMAIN + image_name
            print(image_url)
            CommodityImg.objects.create(img_url=image_url, commodity=commodity)

            return Response({
                'status': status.HTTP_201_CREATED,
                'data': image_url,
            })
    @action(methods=['get'],detail = False)
    def get_commodity_data(self, request):
        commodity = Commodity.objects.filter(classification2=request.GET.get('classification2'))
        if commodity:
            serializers = CommoditySerializer(commodity,many=True)
            return Response({
                'status':status.HTTP_201_CREATED,
                'data':serializers.data
            })
        else:
            return Response(status=status.HTTP_404_NOT_FOUND)
    @action(methods=['get'],detail=False)
    def inites(self,request):
        serializer = self.get_serializer(self.get_queryset(),many = True)
        for i in serializer.data:
            en.index(index='commodity',id=i['id'],body=i)
        return Response(serializer.data)
    @action(methods=['get'],detail=False)
    def search(self,request):
        query={
            "query":{
                "match":{

                }
            },
            "highlight" :{
                "pre_tags": "<span style='color:red'>",
                "post_tags": "</span>",
                "fields": {
                    "name": {}
                }
            }
        }
        if request.GET.get('name'):
            query['query']['match'] = {
                "name": request.GET.get('name')
            }
        else:
            query['query']['match_all'] = {}
            return Response(query['query']['match_all'])

        es_res = en.search(index='commodity', body=query)
        count = es_res['hits']['total']['value']
        results = [self.highlight(i) for i in es_res['hits']['hits']]
        data = {
            'count': count,
            'results': results
        }
        return Response(data)

    def highlight(self, i):
        if i.get('highlight'):
            i['_source']['name'] = i['highlight']['name'][0]
        return i['_source']


